package com.zyit.controller;


import com.zyit.model.SysUsers;
import com.zyit.service.SysUsersService;
import com.zyit.util.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("sysusers")
public class SysUsersController {

    @Resource
    private SysUsersService sysUsersService;

    @GetMapping("findAll")
    public List<SysUsers> finAll(){
        List<SysUsers> all = sysUsersService.findAll();
        System.out.println(all);
        return all;
    }

    /**
     * 管理员添加用户
     */
    @GetMapping("addUser")
    public Result addUser(SysUsers sysUsers){
        sysUsers.setUserType(2);
        int i = sysUsersService.addUser(sysUsers);
        return new Result(200,i,"");

    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("pageUser")
    public List<SysUsers> pageUser(@RequestParam(name = "page", defaultValue = "0") int page,
                                       @RequestParam(name = "size", defaultValue = "10") int size) {
        return sysUsersService.pageAll(page, size);
    }

    /**
     * 登录
     * @param
     * @param
     * @return
     */

    @PostMapping("login")
    public Result login(SysUsers sysUsers ,HttpServletRequest request) {

        SysUsers login = sysUsersService.login(sysUsers);

        if (login != null) {
            // 获取HttpSession对象
            HttpSession session = request.getSession();
            // 将用户信息存入Session
            session.setAttribute("user", login);

            return new Result(200, login, "");
        } else {
            return new Result(401, null, "");
        }
    }


    /**
     * 注销
     */
    @PostMapping("logout")
    public Result logout(HttpServletRequest request) {

        HttpSession session = request.getSession(false);

        if (session != null) {
            // 在需要的情况下，你可以从Session中获取用户信息
            SysUsers loggedInUser = (SysUsers) session.getAttribute("user");
            System.out.println(loggedInUser);
            // 执行注销操作
            session.invalidate();

            System.out.println("User logged out: " + (loggedInUser != null ? loggedInUser.getAccount() : "Unknown User"));

            return new Result(200, null, "");
        } else {
            return new Result(401, null, "");
        }
    }
}
